package com.huiyin.ui.classic;

import java.util.List;

import org.apache.http.Header;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.adapter.DianPingReplayAdapter;
import com.huiyin.adapter.DianPingReplayAdapter.IReplayCallback;
import com.huiyin.api.CustomResponseHandler;
import com.huiyin.api.RequstClient;
import com.huiyin.base.BaseActivity;
import com.huiyin.bean.Review;
import com.huiyin.ui.user.LoginActivity;
import com.huiyin.utils.JSONParseUtils;
import com.huiyin.wight.XListView;
import com.huiyin.wight.XListView.IXListViewListener;

/**
 * 点评晒单-回复
 * 
 * @author 刘远祺
 * 
 * @todo TODO
 * 
 * @date 2015-8-13
 */
public class DianPingReplayActivity extends BaseActivity implements OnClickListener {
	private static final String TAG = "DianPingShaiDan";

	/** 评论ID **/
	public static final String Comment_ID 	= "comment_id";

	/** 类型 **/
	public static final String TYPE 		= "type";

	/** 商品ID **/
	public static final String GOODSID 		= "goodsId";
	
	/** 评价数量 **/
	public static final String COUNT 		= "count";
	

	/** 回复评论ListView **/
	private XListView data_listview;

	/** 评论内容 **/
	private EditText comment_edittext;

	/** 发送 **/
	private Button send;

	/** 点评回复适配器 **/
	private DianPingReplayAdapter adapter;

	
	/**商品ID**/
	private String goodsId;
	
	/** 评论ID*/
	private String commentId;
	
	/**1评论的回复  2追加评论的回复**/
	private String type;
	
	/**回复总数量-这个值在发送回复后台会返回**/
	private String replayTotal;
	
	/**页码**/
	private int pageIndex = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.dian_ping_shai_dan_replay);
		setTitle("回复");
		
		//初始化控件
		initView();
		
		//初始化数据
		initData();
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		data_listview = (XListView) findViewById(R.id.data_listview);
		data_listview.hideFooter();
		data_listview.setPullRefreshEnable(true);
		data_listview.setPullLoadEnable(false);
		data_listview.setXListViewListener(new IXListViewListener() {
			
			@Override
			public void onRefresh() {
				pageIndex = 1;
				getData(pageIndex);
			}
			
			@Override
			public void onLoadMore() {
				//加载下一页
				getData(pageIndex);
			}
		});
		
		comment_edittext = (EditText) findViewById(R.id.comment_edittext);
		send = (Button) findViewById(R.id.send);
		send.setOnClickListener(this);
		
		adapter = new DianPingReplayAdapter(this);
		data_listview.setAdapter(adapter);
		adapter.setOnReviewCallback(new IReplayCallback() {
			
			@Override
			public void onReview(Review review) {
				
				String hint = "回复  "+ review.getUSER_NAME() +":";
				comment_edittext.setHint(hint);
				comment_edittext.setText("");
				comment_edittext.setTag(review.ID);
				
				//文本框获得焦点
				comment_edittext.requestFocus();
				
				//弹起键盘
				InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				inputManager.showSoftInput(comment_edittext, 0);
			}
		});
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		
		//获取参数
		commentId = getStringExtra(Comment_ID);
		type = getStringExtra(TYPE);
		goodsId = getStringExtra(GOODSID);
		
		//获取回复数据
		getData(pageIndex);
	}

	
	/**
	 * 查询评价列表数据
	 * @param loadPageIndex
	 * @param flag
	 */
	public void getData(final int loadPageIndex) {

		
		RequstClient.queryGoodsReviewReply(10, loadPageIndex, goodsId, type, commentId, new CustomResponseHandler(this) {
			@Override
			public void onSuccess(int statusCode, Header[] headers, String content) {
				super.onSuccess(statusCode, headers, content);
				
				//listview刷新head foot
				data_listview.stopLoadMore();
				data_listview.stopRefresh();
				
				if(isSuccessResponse(content)){
					
					//解析回复数据
					List<Review> dataList = JSONParseUtils.parseReviewList(content);
					
					//pageIndex叠加
					pageIndex += (null != dataList && dataList.size() > 0) ? 1 : 0;
					
					//loadPageIndex 1代表下拉刷新，loadPageIndex大于1代表上拉加载
					if(loadPageIndex <= 1){
						adapter.setData(dataList);
					}else{
						adapter.appendData(dataList);
					}
					
					
					//设置listview的下拉，上拉属性
					if(dataList.size() < 10){
						data_listview.hideFooter();
						data_listview.setPullLoadEnable(false);
						data_listview.setPullRefreshEnable(true);
					}else{
						data_listview.showFooter();
						data_listview.setPullLoadEnable(true);
						data_listview.setPullRefreshEnable(true);
					}
				}
			}
			
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send:
			
			//发送评论
			sendComment();
			
			break;
		}
	}

	/**
	 * 发送评论回复
	 */
	private void sendComment(){
		
		if(null == AppContext.userId){
			Toast.makeText(mContext, "请先登录", Toast.LENGTH_LONG).show();
			
			//跳转到登录页面
			Intent intent = new Intent(mContext,LoginActivity.class);
			intent.putExtra(LoginActivity.TAG_Action, LoginActivity.Login_To_Finish);
			mContext.startActivity(intent);
			return;
		}
		
		
		String content = comment_edittext.getText().toString().trim();
		if(TextUtils.isEmpty(content)){
			showMyToast("请输入回复内容");
			return;
		}
		
		String eva_goods_id = commentId;
		String eva_reply_id = (null == comment_edittext.getTag()) ? "-1" : comment_edittext.getTag().toString().trim();
		String type = this.type;
		String userId = AppContext.userId;
		String user_type = "1";//在App端就是普通的会员，所以默认传1
		
		RequstClient.evaReplyGoods(eva_goods_id, eva_reply_id, content, type, userId, user_type, new CustomResponseHandler(this, false) {
			@Override
			public void onSuccess(int statusCode, Header[] headers, String content) {
				super.onSuccess(statusCode, headers, content);
				if(isSuccessResponse(content)){
					showMyToast("发送成功");
					
					comment_edittext.setText("");
					comment_edittext.setHint("说点什么...");
					comment_edittext.setTag(null);
					
					//有数据则解析数据，将这条记录，添加到最前面
					if(content.contains("replay_map")){
						
						adapter.addNewReview(new Review(content));
						//让ListView自动滚动到第一条数据
						if(adapter.getCount() > 0){
							data_listview.setSelection(0);
						}
					}
					
					//获取当前回复的总数量
					replayTotal = JSONParseUtils.getString(content, "reply_num");
				}
			
			}
			
		});
	}
	
	@Override
	public void finish() {
		
		//通知评价晒单刷新数量
		if(!TextUtils.isEmpty(replayTotal)){
			
			//获取到最新的回复数
			Intent data = new Intent();
			data.putExtra(Comment_ID, commentId);
			data.putExtra(TYPE, type);
			data.putExtra(GOODSID, goodsId);
			data.putExtra(COUNT, replayTotal);
			setResult(RESULT_OK, data);
		}
		
		super.finish();
	}
}
